{-# LANGUAGE DeriveDataTypeable #-}

module Language.Dependencies.Adaptors.Map
  ( languagemap
  , name
  , syntax
  , exts
  , parse
--  , toTree
  , srcLoc
  , adjustSrcLoc
  , srcLoctype
  , typerep
  , parseMap
  , module Language.Map.Map
  , module Language.Map.MapPretty
  ) where

-- container
import Data.Tree (Tree(Node,rootLabel))

-- syb
import Data.Generics (Data)

--import Language.Dependencies.DataTree (data2tree)
import Language.Dependencies.Term2tree (data2tree)

-- local imports
import Language.Dependencies.Language

-- Parsec (CSV Parser)
import Text.ParserCombinators.Parsec as Parsec hiding (parse)

import Language.Map.Map
import Language.Map.MapPretty

 
import Data.Generics hiding (Infix)
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language (javaStyle)
import Text.ParserCombinators.Parsec.Expr

languagemap = Language 
            { name=  "Map" 
            , syntax = [] 
            , exts = [".map"] 
            , parse = parseMap
            , toTree = (data2tree TheMap :: Map -> Tree String)
            , srcLoc       = toSrcLoc
            , adjustSrcLoc = Nothing
            , srcLoctype   = (Coordinate undefined undefined) 
            , typerep = Just (TheMap)
            }
             
parseMap :: String -> Either Error Map
parseMap s = case runParser mapParser () "user_input" s of
   Right p -> Right p
   _       -> Left Err

mapParser = mapList <|> mapp

{-  Old version using Offset - now replaced by SourceSpan / Coordinate
toSrcLoc :: Tree String -> [Loc]
toSrcLoc (Node ('O':label) cs ) = [OffSet (read l :: Int) (read r :: Int)] where
                        [l,r] = words label
toSrcLoc _ = []
-}

toSrcLoc :: Tree String -> [Loc]
toSrcLoc (Node "SrcSpan" [ srcFrom, srcTo ]  ) = return $ Coordinate (fst $ extract srcFrom, snd $ extract srcFrom) (fst $ extract srcTo, snd $ extract srcTo) 
toSrcLoc _ = []

extract (Node (srcSpan) cs ) = ((read line :: Int),(read column :: Int))
                               where
                                 srcLoc = words srcSpan
                                 line = init (srcLoc !! 2)
                                 column = init (srcLoc !! 4)
